/**
 *
 */
$(function(){
    $(document).keyup(function (e) {
        if(e.which==13){
            $('#selectBtnEnter').click();
        }
    })
});
var path = '../';
var pageListUrl = path + 'pRecord/list';
var pageListUrl1 = path + 'pRecord/list1';
var pageUrl = path + 'pRecord/';

//添加弹窗
var addPanel = null;
// ---------------交互代码begin-----------------
//本页面业务逻辑
var contract={
    checkLogic:function(dataObj){
        //清除历史错误提示
        dataObj.conCodeErr="";
        dataObj.advCodeErr="";
        dataObj.sexErr="";
        dataObj.minAgeErr="";
        dataObj.maxAgeErr="";
        dataObj.executeTotalErr="";
        dataObj.playTimeErr="";
        dataObj.conTypeErr="",
            dataObj.launchDateErr="";
        dataObj.endDateErr="";
        dataObj.executeNoDateErr="";
        dataObj.executeOffDateErr="";
        dataObj.executeOffDateErr="";
        dataObj.playTimeErr="";
        dataObj.conCodeErr="";
        var isSubmit=true;
        return isSubmit;
    },
    checkFileType:function () {
        var fileName = $("#file")[0].files[0].name;
        var fileType = fileName.substr(fileName.lastIndexOf(".") + 1,fileName.length);
        if(fileType.toUpperCase() != 'XLSX' && fileType.toUpperCase() != 'XLS'){
            importVue.fileErr = "请选择*.xlsx或者*.xls格式的Excel文件";
            return false;
        }
        return true;
    },
    checkFile:function () {
        var fileName = $("#filed")[0].files[0].name;
        var fileType = fileName.substr(fileName.lastIndexOf(".") + 1,fileName.length);
        if(fileType.toUpperCase() != 'XLSX' && fileType.toUpperCase() != 'XLS'){
            importVue1.fileErr = "请选择*.xlsx或者*.xls格式的Excel文件";
            return false;
        }
        return true;
    }
};

//绑定列表List---begin----所有的操作都围绕列表展开，新增、更新其他比较独立
var dataList=new Vue({
    el:"#contractList",
    data:{
        pageInfo : {},
        //TODO 自定义条件查询---begin--------
        condition:{
            page:1,
            rows:customUtils.pageSize,
            id:"",
            postionCode:"",
            advCode:"",
            equipmentCode:"",

            playDate:"",

            startDate:"",
            overDate:"",
            param1:"",//province
            param2:"",//city
            param3:"",//area

            items:[],
            all:false,

        },
        msg: {
            sysErrorMsg: "",
            checkErrMsg: "",
            fieldErrMsg: "",
            success: ""
        },
        //自定义条件查询---end--------
        selectIds:[],//多选
        showSuccess:false,//false不显示成功提示
        selectedIdx:-1,//保存操作行的索引
        isSearch:false,//init:页面初始化；search:点击查询；paging:点击翻页；changePageSize:改变页面显示条数
        selectedPageSize:customUtils.pageSize//修改页面数据显示条数
    },
    mounted: function () {
        //初始化页面数据
        // this.getAreaData();
        this.getList('init');
    },
    // 在 `methods` 对象中定义方法,如果操作中函数的逻辑比较复杂，必须封装到dictType对象
    methods:{
        changeTime:function(elem){
            dataList.$data.condition[elem.split('-')[0]] = $("#"+elem).val();
            console.log(dataList.$data.condition);
        },

        selectChkBtn:function(e){//用于多选事件
            this.selectIds.push($(e.target).val());
        },
        getAreaData:function () {
            this.$http.get("../contract/queryAreaTree").then(function(response){
                console.log(response)
                dataList.$data.condition.provinces = response.body;
                console.log(dataList.$data)
            },function (res) {

            });
        },
        setCitys:function () {
            dataList.$data.condition.citys = dataList.$data.condition.province.citys;
            dataList.$data.condition.city = "";
            dataList.$data.condition.area = "";
            dataList.$data.condition.startDate = "";
            dataList.$data.condition.overDate = "";
            dataList.$data.condition.key = "";
            dataList.$data.condition.status = "";
            dataList.$data.condition.conType = "";
        },
        setAreas:function () {
            dataList.$data.condition.areas = dataList.$data.condition.city.areas;
            dataList.$data.condition.area = "";
        },
        exportContract:function () {
            var self=this;
            var key = self.condition["key"];
            var status = self.condition["status"];
            var startDate = self.condition["startDate"];
            var overDate = self.condition["overDate"];
            var conType = self.condition["conType"];
            location.href=pageUrl+"exportContract?key="+key+"&status="+status+"&startDate="+startDate+"&overDate="+overDate+"&conType="+conType;
        },
        //搜索、分页列表
        getList:function(eventSrc){
            var self=this;
            //改变页面显示条数
            if(eventSrc=="changePageSize"){
                if(this.pageInfo.pageSize != this.selectedPageSize){
                    this.pageInfo.pageSize=this.selectedPageSize;
                    $('#pagination').jqPaginator('destroy');
                    eventSrc='init';//重新绘制控件status
                    return;
                }
            }
            //初始化时无当前页数，后台有默认第1页，每页10条
            if(this.pageInfo!=undefined && this.pageInfo.pageNum!=undefined){
                self.condition["page"]=this.pageInfo.pageNum;
                self.condition["rows"]=this.pageInfo.pageSize;
            }
            var param = {};
            param["page"] = self.condition["page"];
            param["rows"] = self.condition["rows"];
            param["advCode"] = self.condition["advCode"];
            param["status"] = self.condition["status"];
            param["conType"] = self.condition["conType"];
            param["startDate"] = self.condition["startDate"];
            param["overDate"] = self.condition["overDate"];
            param["advCode"] = self.condition["advCode"];
            this.condition.items = [];
            console.log(param)
            //查询请求
            //发送请求,第一个参数http对象，第二个是url，第三个是参数，第四个是成功回调，第五个是请求失败回调
            customUtils.post(self,pageListUrl,param,function(response,isSuccess){
                //isSuccess代表此请求是否成功
                console.log(param);
                console.log(pageListUrl);
                if(isSuccess==false) {
                    dataList.pageInfo.pages = 0;
                    customUtils.noData('无数据', 0);
                    return;
                }
                dataList.pageInfo = response.body.pagination;
                customUtils.noData('无数据',dataList.pageInfo.pages);
                //页面初始化、搜索时，才需要执行分页控件
                if(eventSrc=='init' || eventSrc=='search'){
                    customUtils.paging('#pagination',dataList.pageInfo.pages,customUtils.showPage,function(num){
                        //当前页码pageNum与将要翻页的页码num不相等才执行，否则为同一页
                        if(dataList.pageInfo.pageNum!=num){
                            dataList.pageInfo.pageNum=num;
                            dataList.getList('paging');
                        }
                    });
                }
            },function(response){
                console.log(response);
                dataList.pageInfo.pages=0;
                customUtils.noData('无数据',0);
            });
        },

        importPostion:function(){
            var obj3 = document.getElementById('file') ;
            obj3.outerHTML=obj3.outerHTML;
            importVue.fileErr = "";
            importPanel = layer.open({
                type : 1,
                title :"导入合同信息",
                area : [ '600px', '70%' ],
                shadeClose : false, // 点击遮罩关闭
                content : $('#importPanel')
            });
        },


        // postion:function(index){
        //       console.log(index);
        //       var record = this.pageInfo.list[index];
        //       importVue1.$data.conCode=record.conCode;
        //       console.log(importVue1.$data.conCode);
        //       var obj3 = document.getElementById('file') ;
        //       obj3.outerHTML=obj3.outerHTML;
        //        importVue1.fileErr = "";
        //       importPanel1 = layer.open({
        //           type : 1,
        //           title :"合同分配",
        //           area : [ '600px', '70%' ],
        //           shadeClose : false, // 点击遮罩关闭
        //           content : $('#importPanel1')
        //       });
        //  },
        //批量删除
        deleteAll: function () {
            console.log(status);
            console.log(this.$data.ids);
            var size = dataList.condition.items.length;
            if(size <= 0){
                this.$data.msg.checkErrMsg="请勾选广告信息";
                customUtils.showTips(this.$data.msg,null,3000);
                return;
            }
            var msg = "您确定要将" + size + " 条广告信息删除吗";
            var self = this;
            layer.confirm(msg, function (index) {
                var param = {};
                param["items"] = JSON.stringify(dataList.condition.items);
                customUtils.post(self, pageUrl + "deleteAll", param, function (response, isSuccess) {
                    customUtils.showTips(response.body,null,3000);
                    dataList.getList('no');
                }, function (response) {
                    customUtils.showRequestTips(response, 3000)
                });
                layer.close(index);
                return true;
            });
            return false;
        },
        postion1:function(){
            var obj3 = document.getElementById('filed') ;
            obj3.outerHTML=obj3.outerHTML;
            importVue1.fileErr = "";
            importPanel1 = layer.open({
                type : 1,
                title :"合同分配",
                area : [ '600px', '70%' ],
                shadeClose : false, // 点击遮罩关闭
                content : $('#importPanel1')
            });
        },

        //更新状态
        updateStatus:function(status){
            var size = dataList.condition.items.length;
            if(size <= 0){
                return;
            }
            var str = status==1?"有效":"无效";
            var msg = "您确定要将" + size + " 条位置信息置为<" + str + ">状态";
            var self=this;
            layer.confirm(msg,function (index) {
                var param = {};
                param["items"] = JSON.stringify(dataList.condition.items);
                param["status"] = status;
                customUtils.post(self,pageUrl + "/updateStatus",param,function(response,isSuccess){
                    console.log(response) ;
                    console.log(isSuccess);
                    dataList.getList('init');
                },function (response) {
                    customUtils.showRequestTips(response,3000)
                });
                layer.close(index);
                return true;
            });


            return false;

        },
        //删除
        deleteER:function(index){
            var self=this;
            layer.confirm("你确定要删除这条数据么",function (idx) {
                var record = self.pageInfo.list[index];
                var param = {id:record.id};
                customUtils.post(self,pageUrl + 'deleteER',param,function(response,isSuccess){
                    record.status=status;
                    //根据需要刷新页面数据
                    dataList.getList('no');
                },function(response){
                    //console.log(response.body);
                });
                layer.close(idx);
            })
        },
        //全选--取消全选方法
        checkAll:function () {
            console.log(this.condition);
            if(this.condition.all){
                this.condition.all = false;
                $("tbody").find("input[type='checkbox'][name='id']").each(function(i,val){
                    dataList.condition.items = [];
                });
            }else{
                this.condition.all = true;
                $("tbody").find("input[type='checkbox'][name='id']").each(function(i,val){
                    dataList.condition.items[i] = val.value;
                });
            }
        },
//初始化更新，更新对话框
        updateInit:function(index){
            //先显示窗口，才有加载效果
            this.addOrUpdatePanel("update");
            var record = this.pageInfo.list[index];

            this.selectedIdx=index;
            var url = pageUrl + 'id/'+record.id;
            console.log(record.id);
            var self=this;
            customUtils.get(self.$http,url,function(response,isSuccess){
                console.log(response) ;
                if(isSuccess==false){
                    return;
                }
                //回显表单数据
                $.each(response.body, function(key) {
                    if(addOrUpdate[key]!==undefined && response.body[key]){
                        addOrUpdate[key] = response.body[key];
                    }
                });
                console.log(addOrUpdate.$data)
            },function(response){
                console.log(response);
            });
        },
        tjt: function(){
            // 直接跳转
            var startDate = document.getElementById('startDate-d').value;
            var overDate = document.getElementById('overDate-d').value;
            var advCode = document.getElementById('advCode').value;
            var paths = path + 'page/playbackRecordTrigger.html?';
            if(advCode != ""){
                paths += 'advCode='+advCode;
            }
            if(startDate != ""){
                paths += '&startDate='+startDate;
            }
            if(overDate != ""){
                paths += '&overDate='+overDate;
            }
            window.location.href = paths;
        }
    }
});
//绑定列表List---end----

//新增或更新---------begin-------
var addOrUpdate = new Vue({
    el:"#addPanel",
    data:{
        conCode:"",
        advCode:"",
        executeTotal:"",
        playTime:"",
        executeFrequency:"",
        sex:"",
        minAge:"",
        maxAge:"",
        launchDate:"",
        conType:"",
        endDate:"",
        status:"",
        price:"",
        id:"",
        executeNoDate:"",
        executeOffDate:"",
        //以下是错误信息
        conCodeErr:"",
        advCodeErr:"",
        executeTotalErr:"",
        playTimeErr:"",
        conTypeErr:"",
        executeFrequencyErr:"",
        sexErr:"",
        priceErr:"",
        minAgeErr:"",
        maxAgeErr:"",
        launchDateErr:"",
        endDateErr:"",
        statusErr:"",
        executeNoDateErr:"",
        executeOffDateErr:"",
        showSuccess:true,//显示成功提示
    },
    //当需要在数据变化时执行异步或开销较大的操作时，这个方式是最有用的
    watch:{
    },
    methods:{
        changeTime:function(elem){
            addOrUpdate[elem.split('-')[0]] = $("#"+elem).val();
        },
        typeChange:function () {
            var b = addOrUpdate.$data.conType;
            if(b == 5){
                $("#t5").show();
                // $("#t_age").show();
                // $("#t_sex").show();
                // $("#tl").html("顶部图片：")
                // $("#ml").html("中部视频：")
                // $("#topImg").prop("multiple",false);
            }else{
                $("#t5").hide();
            }
            // if(b ==2){

            //     $("#t_age").hide();
            //     $("#t_sex").hide();
            //     $("#tl").html("前景图片：")
            //     $("#ml").html("背景音乐：")
            //     // $("#topImg").prop("multiple",true);
            // }
        },
        save:function(){
            //逻辑校验
            if(!contract.checkLogic(this.$data)){
                return;
            }
            //没有id的时候表示新增，否则为更新
            var actionUrl=this.id=="" ? 'save' :'update';
            var self=this;
            customUtils.post(self,pageUrl + actionUrl,self.$data,function(response,isSuccess){
                customUtils.showTips(response.body,addOrUpdate.$data,3000)
                console.log(response)
                console.log(isSuccess);
                if(actionUrl=='update'){
                    var record = dataList.pageInfo.list[dataList.selectedIdx];
                    //更新成功，刷新列表中对应的数据
                    $.each(record, function(key) {
                        if(addOrUpdate[key]!=undefined){
                            record[key]=addOrUpdate[key];
                        }
                    });
                }else if(isSuccess){
                    dataList.getList('init');
                }
                if(isSuccess && addPanel)layer.close(addPanel);
            },function(res){
                //console.log(response.body);
            });
        },
        //清除表单数据
        reset:function(){
            $.each(addOrUpdate.$data, function(key) {
                addOrUpdate[key]="";
            });
        }
    }
});

//本页面业务逻辑
var postion = {
    checkLogic: function (dataObj) {
        var result = "";
        var isSubmit = true;
        //TODO 逻辑校验，去掉不必要的:
        //检查表单是否存在错误
        $.each(dataObj, function (key) {
            if (key.indexOf('Err') != -1 && dataObj[key].length > 0) {
                return false;
            }
        });
        return isSubmit;
    },
    checkFileType: function () {
        var fileName = $("#file")[0].files[0].name;
        var fileType = fileName.substr(fileName.lastIndexOf(".") + 1, fileName.length);
        if (fileType.toUpperCase() != 'XLSX' && fileType.toUpperCase() != 'XLS') {
            importVue.fileErr = "请选择*.xlsx或者*.xls格式的Excel文件";
            return false;
        }
        return true;
    }
};

//新增或更新---------end-------
var importVue = new Vue({
    el: "#importPanel",
    data: {
        fileErr: ""
    },
    methods: {
        importB: function () {
            var self = this;
            if (!postion.checkFileType()) {
                return;
            }
            console.log($("#importPanel"))
            console.log($("#importPanel").find("#file")[0].files)
            var formDate = new FormData($("#importPanel")[0]);
            //没选择文件时
            if ($("#importPanel").find("#file")[0].files.length <= 0) {
                $(".errMsg").html("请选择要上传的数据文件");
                return;
            }
            customUtils.post(self, pageUrl + "upload", formDate, function (response) {
                console.log(response);
                dataList.$data.condition.advCode = response.body.advCode;
                customUtils.showTips(response.body, null, 2000);
                var html = "";
                if (response.body.errList != 'undefined' && response.body.errList != '' && response.body.errList != null) {
                    response.body.errList.forEach(function (value, index) {
                        html = html + value + "<br>";
                    });
                    $(".errMsg").html(html);
                } else {
                    if (importPanel) layer.close(importPanel);
                    dataList.getList('init');
                }
            }, function (response) {
                customUtils.showRequestTips(response, 3000)
            })
            console.log(formDate);
        }
    }
})